package com.zmn.oms.third.dj58.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.zmn.common.constant.StatusConsts;
import com.zmn.common.utils.date.DateUtil;
import com.zmn.oms.business.interfaces.notifylog.OrderNotifyLogBService;
import com.zmn.oms.business.interfaces.remark.OrderRemarkBService;
import com.zmn.oms.common.constant.OrderConsts;
import com.zmn.oms.common.constant.OrderStatusConsts;
import com.zmn.oms.common.dto.ResultDTO;
import com.zmn.oms.common.exception.OmsBaseException;
import com.zmn.oms.model.entity.notifylog.OrderNotifyLog;
import com.zmn.oms.model.entity.work.OrderWork;
import com.zmn.oms.model.entity.work.OrderWorkLogChange;
import com.zmn.oms.model.vo.remark.OrderRemarkDetailVO;
import com.zmn.oms.model.vo.remark.OrderRemarkVO;
import com.zmn.oms.services.interfaces.work.OrderWorkService;
import com.zmn.oms.third.dj58.DaoJia58Consts;
import com.zmn.oms.third.dj58.dto.DaoJia58UpdateRepairDTO;
import com.zmn.oms.third.dj58.dto.api.DaoJia58Response;
import com.zmn.oms.third.dj58.service.DaoJia58ReworkService;
import com.zmn.oms.third.dj58.service.DaoJia58Service;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.LinkedList;
import java.util.List;
import java.util.Objects;

/**
 * @author huangyifeng
 * @Description
 * @date 2020/4/13 20:57
 */
@Slf4j
@Service
public class DaoJia58ReworkServiceImpl implements DaoJia58ReworkService {

    @Autowired
    protected OrderWorkService orderWorkService;

    @Autowired
    private DaoJia58Service daoJia58Service;

    @Autowired
    private OrderNotifyLogBService orderNotifyLogBService;

    @Autowired
    private OrderRemarkBService orderRemarkBService;


    @Override
    public void sendCancelReworkOrder(OrderWorkLogChange orderWorkLogChange) throws OmsBaseException {
        // 获取工单信息
        OrderWork orderWork = findOrderWork(orderWorkLogChange.getOrderId(), orderWorkLogChange.getWorkId());

        DaoJia58UpdateRepairDTO updateRepairDTO = new DaoJia58UpdateRepairDTO();
        updateRepairDTO.setOrderId(Long.parseLong(orderWork.getOuterId()));
        updateRepairDTO.setInsureId(orderWorkLogChange.getExtOuterData());
        updateRepairDTO.setOrgId(DaoJia58Consts.ORG_ID);
        updateRepairDTO.setRepairId(orderWork.getOrderId().toString());
        // 1：成功， 2：失败
        updateRepairDTO.setRepairType(2);
        updateRepairDTO.setRepairTime(orderWorkLogChange.getOpTime().getTime());

        // 取消备注（原因），需要将手写备注和选项备注进行拼接
        OrderRemarkVO orderRemarkVO = orderRemarkBService.findOrderRemarkVO(orderWork.getOrderId(), orderWork.getOrderId(),
                OrderConsts.ORDER_REMARK_TYPE_CANCEL);
        List<String> remarkList = new LinkedList<>();
        if (StringUtils.isNotBlank(orderRemarkVO.getContent())) {
            remarkList.add(orderRemarkVO.getContent());
        }
        if (orderRemarkVO.getDetailVOList() != null) {
            for (OrderRemarkDetailVO item : orderRemarkVO.getDetailVOList()) {
                remarkList.add(item.getMapName());
            }
        }
        String remark = (remarkList.size() > 0) ? StringUtils.join(remarkList, "，") : null;
        updateRepairDTO.setFailReason(remark);

        // 同步消息
        String paramJson = JSON.toJSONString(updateRepairDTO, SerializerFeature.SortField.MapSortField);
        DaoJia58Response responseRequest = daoJia58Service.sendRequestTo58DaoJia(DaoJia58Consts.REWORK_ORDER_PATH,
                paramJson);

        if (Objects.isNull(responseRequest) || responseRequest.getCode() != DaoJia58Consts.DAOJIA58_RETURN_CODE_SUCCESS) {
            throw new OmsBaseException(DaoJia58Consts.ERROR_CODE_SEND_REQUEST_FAILED, "同步返修订单取消消息失败");
        }

        this.saveSyncResult(orderWorkLogChange, OrderStatusConsts.ORDER_STATUS_CANCEL, responseRequest);
    }

    @Override
    public void sendCompleteReworkOrder(OrderWorkLogChange orderWorkLogChange) throws OmsBaseException {
        Long orderId = orderWorkLogChange.getOrderId();
        Long workId = orderWorkLogChange.getWorkId();

        // 获取工单信息
        OrderWork orderWork = findOrderWork(orderId, workId);

        DaoJia58UpdateRepairDTO updateRepairDTO = new DaoJia58UpdateRepairDTO();
        updateRepairDTO.setOrderId(Long.parseLong(orderWork.getOuterId()));
        updateRepairDTO.setInsureId(orderWorkLogChange.getExtOuterData());
        updateRepairDTO.setOrgId(DaoJia58Consts.ORG_ID);
        updateRepairDTO.setRepairId(orderWork.getOrderId().toString());
        // 1：成功， 2：失败
        updateRepairDTO.setRepairType(1);
        updateRepairDTO.setRepairTime(orderWorkLogChange.getOpTime().getTime());

        updateRepairDTO.setMoney("0");  // 返修单，价格为0

        String paramJson = JSON.toJSONString(updateRepairDTO, SerializerFeature.SortField.MapSortField);
        DaoJia58Response responseRequest = daoJia58Service.
                sendRequestTo58DaoJia(DaoJia58Consts.REWORK_ORDER_PATH, paramJson);

        if (Objects.isNull(responseRequest) || responseRequest.getCode() != DaoJia58Consts.DAOJIA58_RETURN_CODE_SUCCESS) {
            throw new OmsBaseException(DaoJia58Consts.ERROR_CODE_SEND_REQUEST_FAILED, "同步返修订单完成消息失败");
        }

        this.saveSyncResult(orderWorkLogChange, OrderStatusConsts.ORDER_STATUS_COMPLETE, responseRequest);
    }


    private OrderWork findOrderWork(Long orderId, Long workId) throws OmsBaseException {
        // 获取工单信息
        OrderWork orderWork = orderWorkService.findOrderWorkByKey(orderId, workId);
        if (Objects.isNull(orderWork)) {
            throw new OmsBaseException(DaoJia58Consts.ERROR_CODE_SERVER_UNKNOWN, "查不到对应的工单信息");

        }

        return orderWork;
    }

    /**
     * 保存状态同步结果信息
     *
     * @param orderWorkLogChange
     * @param orderStatus
     * @param result
     */
    @SuppressWarnings("all")
    private void saveSyncResult(OrderWorkLogChange orderWorkLogChange, int orderStatus, DaoJia58Response result) {
        if (Objects.isNull(result) || Objects.isNull(orderWorkLogChange)) {
            return;
        }

        OrderNotifyLog orderNotifyLog = new OrderNotifyLog();
        orderNotifyLog.setMqMsgKey(orderWorkLogChange.getMqMsgKey());
        orderNotifyLog.setOrderId(orderWorkLogChange.getOrderId());
        orderNotifyLog.setChannelId(orderWorkLogChange.getChannelId());
        orderNotifyLog.setOrderStatus(orderWorkLogChange.getStatus());
        orderNotifyLog.setOrderResultStatus(orderWorkLogChange.getResultStatus());
        orderNotifyLog.setNotifyStatus(String.valueOf(orderStatus));
        orderNotifyLog.setType(OrderConsts.ORDER_NOTIFY_TYPE_CHANGE);
        orderNotifyLog.setNotifyTime(DateUtil.getNow());
        orderNotifyLog.setNotifyResultMsg(String.format("[%s]-%s",
                OrderStatusConsts.getOrderStatusName(orderStatus), result.getMessage()));

        ResultDTO resultDTO = new ResultDTO();
        resultDTO.setStatus(result.getCode() == DaoJia58Consts.ZMN_RETURN_CODE_SUCCESS ? StatusConsts.STATUS_SUCCESS : StatusConsts.STATUS_ERROR);
        resultDTO.setData(orderNotifyLog);

        orderNotifyLogBService.saveNotifyLog(resultDTO);
    }
}
